package api

import (
	"RedWork/dao"
	"RedWork/util/errmsg"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
)

func AddComment() gin.HandlerFunc {
	return func(c *gin.Context) {
		status := true
		data := "success"
		gid := c.PostForm("good_id")
		comment := c.PostForm("comment")
		score := c.PostForm("score")
		var info dao.Comment
		token_code, _ := c.Get("token_code")
		if token_code != errmsg.SUCCSE {
			status = false
			data = errmsg.GetErrMsg(token_code.(int))
		} else {
			uid, ok := c.Get("uid")
			if !ok {
				status = false
				data = "未检测到登录信息"
			}
			atoi, err := strconv.Atoi(score)
			if err != nil {
				log.Println(err)
				status = false
				data = errmsg.GetErrMsg(errmsg.PARM_NOT_RIGHT)
			}
			if atoi < 0 || atoi > 5 {
				status = false
				data = errmsg.GetErrMsg(errmsg.PARM_NOT_RIGHT)
			}
			if status {
				info.UserID = strconv.Itoa(uid.(int))
				info.GoodID = gid
				info.CommentInfo = comment
				if score == "" {
					info.Score = "5"
				} else {
					info.Score = score
				}
				err := dao.AddComment(info)
				if err != nil {
					fmt.Println(err)
					status = false
					data = "parm is not right"
				}
			}
		}

		c.JSON(200, gin.H{
			"status": status,
			"data":   data,
		})
	}
}

func QueryComment() gin.HandlerFunc {
	return func(c *gin.Context) {
		status := true
		//data := ""
		gid := c.Query("good_id")
		code := c.Query("code")
		codeint, err := strconv.Atoi(code)
		token_code, _ := c.Get("token_code")
		if token_code != errmsg.SUCCSE {
			status = false
			c.JSON(200, gin.H{
				"status": status,
				"data":   errmsg.GetErrMsg(token_code.(int)),
			})
			c.Abort()
			return
			//data = errmsg.GetErrMsg(token_code.(int))
		} else {
			if code != "" {
				if err != nil {
					fmt.Println(err)
					status = false
					data := errmsg.GetErrMsg(errmsg.PARM_NOT_RIGHT)
					c.JSON(200, gin.H{
						"status": status,
						"data":   data,
					})
				}
			}

		}

		if status {
			c.JSON(200, gin.H{
				"status": status,
				"data":   dao.QueryComment(gid, codeint),
			})
		}
	}
}
